import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Grid,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  Typography,
  Divider,
  Switch,
  FormControlLabel,
  Autocomplete,
  InputAdornment,
  Alert,
} from '@mui/material';
import {
  Save as SaveIcon,
  Cancel as CancelIcon,
  Business as BusinessIcon,
  AccountTree as TreeIcon,
} from '@mui/icons-material';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

import {
  CreateOrganizationRequest,
  Organization,
  Status,
} from '@/types';
import { useAuth, useAppNotifications } from '@/stores';
import { organizationService } from '@/services/organizationService';
import { PageHeader } from '@/components/common/PageHeader';

// 表单验证模式
const organizationFormSchema = z.object({
  name: z.string().min(1, '组织名称不能为空').max(100, '组织名称不能超过100个字符'),
  code: z.string()
    .min(1, '组织编码不能为空')
    .max(50, '组织编码不能超过50个字符')
    .regex(/^[a-zA-Z0-9_-]+$/, '组织编码只能包含字母、数字、下划线和横线'),
  description: z.string().optional(),
  parentId: z.string().optional(),
  status: z.enum(['active', 'inactive', 'pending', 'suspended']),
  sort: z.number().min(0, '排序值不能为负数').max(9999, '排序值不能超过9999'),
  settings: z.object({
    maxUsers: z.number().min(1, '用户数限制不能少于1').max(10000, '用户数限制不能超过10000'),
    maxSubOrganizations: z.number().min(0, '子组织数限制不能为负数').max(1000, '子组织数限制不能超过1000'),
    allowSubOrgCreation: z.boolean(),
    inheritParentSettings: z.boolean(),
    features: z.array(z.string()).optional(),
  }),
  managerUserId: z.string().optional(),
});

type OrganizationFormData = z.infer<typeof organizationFormSchema>;

const OrganizationCreatePage: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const queryClient = useQueryClient();
  const { hasPermission, currentTenant } = useAuth();
  const { showToast } = useAppNotifications();

  const [isSubmitting, setIsSubmitting] = useState(false);
  const parentId = searchParams.get('parentId');

  // 表单控制
  const {
    control,
    handleSubmit,
    formState: { errors },
    watch,
    setValue,
  } = useForm<OrganizationFormData>({
    resolver: zodResolver(organizationFormSchema),
    defaultValues: {
      name: '',
      code: '',
      description: '',
      parentId: parentId || '',
      status: 'active',
      sort: 0,
      settings: {
        maxUsers: 100,
        maxSubOrganizations: 10,
        allowSubOrgCreation: true,
        inheritParentSettings: true,
        features: [],
      },
      managerUserId: '',
    },
  });

  // 监听组织名称变化，自动生成编码
  const organizationName = watch('name');
  useEffect(() => {
    if (organizationName) {
      const code = organizationName
        .toLowerCase()
        .replace(/[^a-z0-9\s]/g, '')
        .replace(/\s+/g, '_')
        .substring(0, 20);
      setValue('code', code);
    }
  }, [organizationName, setValue]);

  // 获取组织列表（用于选择父组织）
  const { data: organizationsData } = useQuery({
    queryKey: ['organizations', { tenantId: currentTenant?.id }],
    queryFn: () => organizationService.getOrganizations({ tenantId: currentTenant?.id }),
    enabled: !!currentTenant,
  });

  // 获取用户列表（用于选择管理员）
  const { data: usersData } = useQuery({
    queryKey: ['users', { organizationId: currentTenant?.id }],
    queryFn: () => fetch(`/api/users?organizationId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 创建组织
  const createMutation = useMutation({
    mutationFn: organizationService.createOrganization,
    onSuccess: (response) => {
      showToast({
        type: 'success',
        title: '创建成功',
        message: '组织已成功创建',
      });
      queryClient.invalidateQueries(['organizations']);
      navigate('/organizations');
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '创建失败',
        message: error.message || '创建组织时发生错误',
      });
    },
  });

  // 提交表单
  const onSubmit = async (data: OrganizationFormData) => {
    if (!hasPermission('organization.create')) {
      showToast({
        type: 'error',
        title: '权限不足',
        message: '您没有创建组织的权限',
      });
      return;
    }

    if (!currentTenant) {
      showToast({
        type: 'error',
        title: '操作失败',
        message: '请先选择租户',
      });
      return;
    }

    setIsSubmitting(true);
    try {
      const requestData: CreateOrganizationRequest = {
        ...data,
        tenantId: currentTenant.id,
      };
      await createMutation.mutateAsync(requestData);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 构建组织树形选项
  const buildOrganizationOptions = (orgs: Organization[], level = 0): Array<{ label: string; value: string; level: number }> => {
    const options: Array<{ label: string; value: string; level: number }> = [];
    
    orgs.forEach(org => {
      const prefix = '　'.repeat(level); // 使用全角空格表示层级
      options.push({
        label: `${prefix}${org.name}`,
        value: org.id,
        level,
      });
      
      const children = orgs.filter(child => child.parentId === org.id);
      if (children.length > 0) {
        options.push(...buildOrganizationOptions(children, level + 1));
      }
    });
    
    return options;
  };

  const organizationOptions = organizationsData?.data 
    ? buildOrganizationOptions(organizationsData.data.filter(org => !org.parentId))
    : [];

  // 可用功能选项
  const availableFeatures = [
    { id: 'advanced_permissions', label: '高级权限管理' },
    { id: 'custom_workflows', label: '自定义工作流' },
    { id: 'data_analytics', label: '数据分析' },
    { id: 'api_access', label: 'API访问' },
    { id: 'custom_branding', label: '自定义品牌' },
    { id: 'audit_logs', label: '审计日志' },
  ];

  if (!currentTenant) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="warning">
          请先选择租户
        </Alert>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="创建组织"
        description="创建新的组织单位"
        breadcrumbs={[
          { label: '首页', path: '/' },
          { label: '组织管理', path: '/organizations' },
          { label: '创建组织' },
        ]}
      />

      <Card>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Grid container spacing={3}>
              {/* 基本信息 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom>
                  基本信息
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="name"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="组织名称"
                      fullWidth
                      required
                      error={!!errors.name}
                      helperText={errors.name?.message}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <BusinessIcon />
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="code"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="组织编码"
                      fullWidth
                      required
                      error={!!errors.code}
                      helperText={errors.code?.message || '系统唯一标识，将根据组织名称自动生成'}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12}>
                <Controller
                  name="description"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="组织描述"
                      fullWidth
                      multiline
                      rows={3}
                      placeholder="请输入组织的详细描述..."
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="parentId"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>上级组织</InputLabel>
                      <Select
                        {...field}
                        label="上级组织"
                        startAdornment={
                          <InputAdornment position="start">
                            <TreeIcon />
                          </InputAdornment>
                        }
                      >
                        <MenuItem value="">无（作为顶级组织）</MenuItem>
                        {organizationOptions.map((option) => (
                          <MenuItem key={option.value} value={option.value}>
                            {option.label}
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="status"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>状态</InputLabel>
                      <Select {...field} label="状态">
                        <MenuItem value="active">启用</MenuItem>
                        <MenuItem value="inactive">禁用</MenuItem>
                        <MenuItem value="pending">待审核</MenuItem>
                        <MenuItem value="suspended">暂停</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="sort"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="排序值"
                      type="number"
                      fullWidth
                      error={!!errors.sort}
                      helperText={errors.sort?.message || '数值越小排序越靠前'}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="managerUserId"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>组织管理员</InputLabel>
                      <Select {...field} label="组织管理员">
                        <MenuItem value="">暂不设置</MenuItem>
                        {usersData?.data?.map((user: any) => (
                          <MenuItem key={user.id} value={user.id}>
                            {user.profile.fullName} ({user.username})
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              {/* 配置设置 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ mt: 2 }}>
                  配置设置
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={4}>
                <Controller
                  name="settings.maxUsers"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="用户数限制"
                      type="number"
                      fullWidth
                      required
                      error={!!errors.settings?.maxUsers}
                      helperText={errors.settings?.maxUsers?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={4}>
                <Controller
                  name="settings.maxSubOrganizations"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="子组织数限制"
                      type="number"
                      fullWidth
                      required
                      error={!!errors.settings?.maxSubOrganizations}
                      helperText={errors.settings?.maxSubOrganizations?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={4}>
                <Box sx={{ pt: 2 }}>
                  <Controller
                    name="settings.allowSubOrgCreation"
                    control={control}
                    render={({ field }) => (
                      <FormControlLabel
                        control={<Switch {...field} checked={field.value} />}
                        label="允许创建子组织"
                      />
                    )}
                  />
                </Box>
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="settings.inheritParentSettings"
                  control={control}
                  render={({ field }) => (
                    <FormControlLabel
                      control={<Switch {...field} checked={field.value} />}
                      label="继承父组织设置"
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12}>
                <Controller
                  name="settings.features"
                  control={control}
                  render={({ field }) => (
                    <Autocomplete
                      multiple
                      options={availableFeatures}
                      getOptionLabel={(option) => option.label}
                      value={availableFeatures.filter(feature => 
                        field.value?.includes(feature.id)
                      )}
                      onChange={(_, newValue) => {
                        field.onChange(newValue.map(item => item.id));
                      }}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="可用功能"
                          placeholder="选择组织可使用的功能..."
                        />
                      )}
                    />
                  )}
                />
              </Grid>

              {/* 操作按钮 */}
              <Grid item xs={12}>
                <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 3 }}>
                  <Button
                    variant="outlined"
                    startIcon={<CancelIcon />}
                    onClick={() => navigate('/organizations')}
                    disabled={isSubmitting}
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    variant="contained"
                    startIcon={<SaveIcon />}
                    disabled={isSubmitting || !hasPermission('organization.create')}
                  >
                    {isSubmitting ? '创建中...' : '创建组织'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Box>
  );
};

export default OrganizationCreatePage;